//
//  ComposeViewController.swift
//  weiboxiangmu
//
//  Created by wei_jingyun on 15/7/8.
//  Copyright © 2015年 wei_jingyun. All rights reserved.
//

import UIKit
import SVProgressHUD

 /// 最大文字长度
private let maxStatusTextLength = 10

class ComposeViewController: UIViewController , UITextViewDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.redColor()
    }
    // MARK: - 点击交互事件
    ///  切换表情视图
    func inputEmoticon() {
        Debug.LogFunc()
    }
    
    ///  选择照片
    func selectPicture() {
        Debug.LogFunc()
    }

    ///  发送微博
    func sendStatus(){
        // TODO: 需要修改 返回 图文混排的文本
        let text = textView.text
        if text.characters.count > maxStatusTextLength {
            NetWorkTools.sharedNetWorkTools().showTextLong()
            return
        }
        
        NetWorkTools.sharedNetWorkTools().show()
        NetWorkTools.sharedNetWorkTools().postStatus(textView.text) {[unowned self] (error) -> () in
            if error != nil {
                return
            }
            self.close()
        }
    }
    
    // MARK: - 加载界面
    override func loadView() {
        view = UIView()
        prepareNavigationBar()
        prepareTextView()
    }

    
    private func prepareTextView(){
        view.addSubview(textView)
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(18)
        textView.ff_edgesView(UIedgeView().more(tlbr: ff_tlbr.all, v: view))
        
        // 设置弹出键盘的辅助视图
        textView.inputAccessoryView = prepareToolBar()
        // 设置垂直滚动
        textView.alwaysBounceVertical = true
        // 滚动关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 加一个占位标签
        placeHolderLabel.text = "分享新鲜事..."
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.ff_edgesView(UIedgeView().top(textView, c: 8).left(textView, c: 5))
        
        //TODO: 需要修改  添加字符长度标签
        textView.inputAccessoryView!.addSubview(lengthLabel)
//        lengthLabel.text = "140"
        lengthLabel.ff_edgesView(UIedgeView().top(textView.inputAccessoryView!, c: -20).right(textView.inputAccessoryView!, c: 10))
    }
    
    private func prepareToolBar() -> UIToolbar {
        let tb = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
        tb.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        // 创建所有按钮数组
        var items = [UIBarButtonItem]()
        // 设置按钮
        for settings in itemSettings {
            items.append(UIBarButtonItem(imageName: settings["imageName"]!, highlightedImageName: nil, target: nil, actionName: settings["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        // 移除最后一个弹簧
        items.removeLast()
        tb.items = items
        return tb
    }

    private func prepareNavigationBar() {
        // 1. 左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        // 2. 右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 3.中间title 显示登录用户的名称
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let label1 = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        label1.text = "发微博"
        
        let label2 = UILabel(color: UIColor.darkGrayColor(), fontSize: 12)
        label2.text = sharedUserAccount?.name ?? ""
        label2.textColor = UIColor(white: 0.0, alpha: 0.5)
        
        titleView.addSubview(label1)
        titleView.addSubview(label2)
        
        label1.ff_edgesView(UIedgeView().top(titleView, c: 0).centerX(titleView, c: 0))
        label2.ff_edgesView(UIedgeView().top(label1, c: 0).centerX(label1, c: 0))
        
        navigationItem.titleView = titleView

    }
    
    // MARK: - 进出时弹出收回键盘
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    
    func textViewDidChange(textView: UITextView){
        // 修改遮挡以及发送状态
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // TODO: 需要修改 返回 图文混排的文本 显示剩余文字
        let length = maxStatusTextLength - textView.text.characters.count
        lengthLabel.text = length == 0 ? "" : String(length)
        lengthLabel.textColor = length > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
    
    // MARK: - 关闭释放控制器
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    deinit {
        Debug.Log("被释放")
    }
    
    // MARK: 懒加载
    private lazy var textView = UITextView()
    private lazy var placeHolderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var lengthLabel = UILabel(color: UIColor.redColor(), fontSize: 12)
}


